<template>
  <div class="app-container">
    <el-form :model="queryParams" ref="queryForm" :inline="true" v-show="showSearch" label-width="68px">
      <el-form-item label="所属栏目" prop="categoryId">
        <el-cascader
          v-model="queryParams.categoryId"
          :options="categoryTree"
          :props="{ checkStrictly: true, expandTrigger: 'hover', value: 'id', label: 'title', emitPath: false }"
          clearable></el-cascader>
      </el-form-item>
      <el-form-item label="类型" prop="type">
        <el-select v-model="queryParams.type" placeholder="请选择类型" clearable size="small">
          <el-option
            v-for="dict in typeOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="内容名称" prop="title">
        <el-input
          v-model="queryParams.title"
          placeholder="请输入内容名称"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="归属" prop="belong">
        <el-select v-model="queryParams.belong" placeholder="请选择归属" clearable size="small" @change="queryBelongChange">
          <el-option
            v-for="dict in belongOptions"
            :key="dict.dictValue"
            :label="dict.dictLabel"
            :value="dict.dictValue"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="所属部门" prop="depart">
        <el-select v-model="queryParams.departId" placeholder="请选择所属部门" clearable size="small">
          <el-option
            v-for="dict in departOptions"
            :key="dict.id"
            :label="dict.name"
            :value="dict.id"
          />
        </el-select>
      </el-form-item>
      <el-form-item label="ID" prop="id">
        <el-input
          v-model="queryParams.id"
          placeholder="请输入id"
          clearable
          size="small"
          @keyup.enter.native="handleQuery"
        />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-select v-model="queryParams.status" placeholder="请选择状态" clearable size="small">
          <el-option key="0" label="审核未通过" value="0"/>
          <el-option key="1" label="审核通过" value="1"/>
          <el-option key="2" label="等待审核" value="2"/>
        </el-select>
      </el-form-item>
      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-row :gutter="10" class="mb8">
      <el-col :span="1.5">
        <el-button
          type="primary"
          plain
          icon="el-icon-plus"
          size="mini"
          @click="handleAdd"
          v-hasPermi="['business:content:add']"
        >新增
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="success"
          plain
          icon="el-icon-edit"
          size="mini"
          :disabled="single"
          @click="handleUpdate"
          v-hasPermi="['business:content:edit']"
        >修改
        </el-button>
      </el-col>
      <el-col :span="1.5">
        <el-button
          type="danger"
          plain
          icon="el-icon-delete"
          size="mini"
          :disabled="multiple"
          @click="handleDelete"
          v-hasPermi="['business:content:remove']"
        >删除
        </el-button>
      </el-col>
      <right-toolbar :showSearch.sync="showSearch" @queryTable="getList"></right-toolbar>
    </el-row>

    <el-table v-loading="loading" :data="contentList" @selection-change="handleSelectionChange">
      <el-table-column type="selection" width="55" align="center"/>
      <el-table-column label="ID" align="center" prop="id"/>
      <el-table-column label="标题" align="center" prop="title"/>
      <el-table-column label="创建时间" align="center" prop="createTime"/>
      <el-table-column label="排序" align="center" prop="sortOrder"/>
      <el-table-column label="所属栏目" align="center" prop="categoryName"/>
      <el-table-column label="类型" align="center" prop="type" :formatter="typeFormat"/>
      <el-table-column label="状态" align="center" prop="status" :formatter="statusFormat"/>
      <el-table-column label="操作" align="center" class-name="small-padding fixed-width">
        <template slot-scope="scope">
          <el-button
            size="mini"
            type="text"
            icon="el-icon-edit"
            @click="handleUpdate(scope.row)"
            v-hasPermi="['business:content:edit']"
          >修改
          </el-button>
          <el-button
            size="mini"
            type="text"
            icon="el-icon-delete"
            @click="handleDelete(scope.row)"
            v-hasPermi="['business:content:remove']"
          >删除
          </el-button>
        </template>
      </el-table-column>
    </el-table>

    <pagination
      v-show="total>0"
      :total="total"
      :page.sync="queryParams.pageNum"
      :limit.sync="queryParams.pageSize"
      @pagination="getList"
    />

    <!-- 添加或修改Content对话框 -->
    <el-dialog :title="title" :visible.sync="open" width="80%" append-to-body :close-on-click-modal="false" modal
               :destroy-on-close="true">
      <el-form ref="form" :model="form" :rules="rules" label-width="160px">
        <el-form-item label="标题" prop="title">
          <el-input v-model="form.title" type="textarea" placeholder="请输入内容"/>
        </el-form-item>
        <el-form-item label="所属栏目" prop="categoryId">
          <el-cascader
            v-model="form.categoryId"
            :options="categoryTree"
            :props="{ checkStrictly: true, expandTrigger: 'hover', value: 'id', label: 'title', emitPath: false }"
            clearable></el-cascader>
        </el-form-item>
        <el-form-item label="类型" prop="type">
          <el-select v-model="form.type" placeholder="请选择类型">
            <el-option
              v-for="dict in typeOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="parseInt(dict.dictValue)"
            ></el-option>
          </el-select>
        </el-form-item>
        <el-form-item label="文本内容" v-if="form.type === 1">
          <tiny-mce v-model="form.content" :input="contentChange"/>
        </el-form-item>
        <el-form-item label="PDF上传" v-if="form.type === 2">
          <pdf-upload v-model="form.content"/>
        </el-form-item>
        <el-form-item label="视频上传" v-if="form.type === 3">
          <video-upload v-model="form.content"/>
        </el-form-item>
        <el-form-item label="文件上传" v-if="form.type === 4">
          <el-upload
            ref="word-upload"
            :accept="upload.fileType"
            :headers="upload.headers"
            :action="upload.url"
            :disabled="upload.isUploading"
            :on-progress="handleFileUploadProgress"
            :on-success="handleFileSuccess"
            :auto-upload="true"
            :multiple="true"
            :file-list="upload.files"
          >
            <i class="el-icon-upload" style="width: 50px;height: 50px;font-size: 50px;"></i>
            <div class="el-upload__tip" style="color:red" slot="tip">提示：仅允许导入"{{ upload.fileType }}"格式文件！</div>
          </el-upload>
        </el-form-item>
        <el-form-item label="外链URL设置" v-if="form.type === 5">
          <div v-for="(webUrl, index) in webUrls" :key="index">
            <div class="el-col el-col-10">
              <el-form-item label="外链名称" label-width="auto" size="small">
                <el-input v-model="webUrl.title" type="text" placeholder="请输入外链名称"/>
              </el-form-item>
            </div>
            <div class="el-col el-col-10 el-col-offset-1">
              <el-form-item label="外链地址" label-width="auto" size="small">
                <el-input v-model="webUrl.url" type="text" placeholder="请输入外链地址"/>
              </el-form-item>
            </div>
            <div class="el-col el-col-2  el-col-offset-1">
              <el-form-item size="small" style="margin-top: 36px;">
                <el-button type="primary" @click="addWebUrl">+</el-button>
                <el-button type="primary" @click="removeWebUrl(index)">-</el-button>
              </el-form-item>
            </div>
          </div>
        </el-form-item>
        <el-form-item label="封面">
          <imageUpload v-model="form.cover"/>
        </el-form-item>
        <el-form-item label="排序" prop="sortOrder">
          <el-input v-model="form.sortOrder" placeholder="请输入排序"/>
        </el-form-item>

<!--        <el-form-item label="来源" prop="source">-->
<!--          <el-cascader-->
<!--            v-model="form.source"-->
<!--            :options="sourceTree"-->
<!--            :props="{ checkStrictly: true, expandTrigger: 'hover', value: 'id', label: 'label', emitPath: false }"-->
<!--            clearable></el-cascader>-->
<!--        </el-form-item>-->

        <el-form-item label="归属" prop="belong">
          <el-select v-model="form.belong" placeholder="请选择归属" @change="formBelongChange">
            <el-option
              v-for="dict in belongOptions"
              :key="dict.dictValue"
              :label="dict.dictLabel"
              :value="dict.dictValue"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="所属部门" prop="departId">
          <el-select v-model="form.departId" placeholder="请选择所属部门">
            <el-option
              v-for="dict in departOptions"
              :key="dict.id"
              :label="dict.name"
              :value="dict.id"
            />
          </el-select>
        </el-form-item>
        <el-form-item label="创建日期和时间" prop="createTime">
          <el-date-picker
            v-model="form.createTime"
            format="yyyy-MM-dd HH:mm:ss"
            type="datetime"
            placeholder="选择日期时间"
            default-time="12:00:00">
          </el-date-picker>
        </el-form-item>

<!--        <el-form-item label="状态">-->
<!--          <el-radio-group v-model="form.status">-->
<!--            <el-radio-->
<!--              v-for="dict in statusOptions"-->
<!--              :key="dict.dictValue"-->
<!--              :label="parseInt(dict.dictValue)"-->
<!--            >{{ dict.dictLabel }}-->
<!--            </el-radio>-->
<!--          </el-radio-group>-->
<!--        </el-form-item>-->
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="primary" @click="submitForm">确 定</el-button>
        <el-button @click="cancel">取 消</el-button>
      </div>
    </el-dialog>
  </div>
</template>

<script>
import {
  listContent,
  getContent,
  delContent,
  addContent,
  updateContent,
  exportContent,
  getSourceTree
} from '@/api/business/content'
import ImageUpload from '@/components/ImageUpload';
import Editor from '@/components/Editor';
import {getCategoryTree} from "@/api/business/category";
import VideoUpload from '@/components/VideoUpload';
import PdfUpload from '@/components/PdfUpload';
import TinyMce from '@/components/TinyMce';
import { getDepartByBelong } from '@/api/business/depart'
import { getToken } from '@/utils/auth'
import moment from 'moment'

export default {
  name: "Content",
  components: {
    ImageUpload,
    Editor,
    VideoUpload,
    PdfUpload,
    TinyMce
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      // 导出遮罩层
      exportLoading: false,
      // 选中数组
      ids: [],
      // 非单个禁用
      single: true,
      // 非多个禁用
      multiple: true,
      // 显示搜索条件
      showSearch: true,
      // 总条数
      total: 0,
      // Content表格数据
      contentList: [],
      // 弹出层标题
      title: "",
      // 是否显示弹出层
      open: false,
      // 类型 1text 2pdf 3video字典
      typeOptions: [],
      // 状态 0禁用 1启用字典
      statusOptions: [],
      // 查询参数
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        title: null,
        categoryId: null,
        position: 2,
        type: null,
        status: null,
        id: null
      },
      // 表单参数
      form: {},
      // 表单校验
      rules: {
        title: [
          { required: true, message: '内容标题不允许为空', trigger: 'blur' }
        ],
        categoryId: [
          { required: true, message: '所属栏目不允许为空', trigger: 'blur' }
        ],
        belong: [
          { required: true, message: '归属不允许为空', trigger: 'blur' }
        ],
        departId: [
          { required: true, message: '所属部门不允许为空', trigger: 'blur' }
        ],
        createTime: [
          { required: true, message: '发布时间不允许为空', trigger: 'blur' }
        ]
      },
      // 栏目树
      categoryTree: [],
      // 部门树
      sourceTree: [],
      belongOptions: [],
      departOptions: [],
      // 用户导入参数
      upload: {
        // 是否禁用上传
        isUploading: false,
        // 设置上传的请求头部
        headers: { Authorization: 'Bearer ' + getToken() },
        // 上传的地址
        url: process.env.VUE_APP_BASE_API + '/common/upload',
        fileType: '.doc,docx,.xls,xlsx,.ppt,.pdf,.dps,.pptx',
        files: []
      },
      webUrls: [{
        title: '',
        url: ''
      }]
    };
  },
  created() {
    this.getCategoryTree();
    this.getList();
    this.getDicts("business_content_type").then(response => {
      this.typeOptions = response.data;
    });
    this.getDicts('business_file_type').then(response => {
      if (response.data.length > 0) {
        let type = response.data.map(item => {
          return item.dictLabel
        }).join(',')
        this.upload.fileType = type
      }
    })
    this.getDicts("business_status").then(response => {
      this.statusOptions = response.data;
    });
    this.getDicts('business_belong').then(response => {
      this.belongOptions = response.data
    })
  },
  methods: {
    moment,
    queryBelongChange(newValue) {
      if (newValue != '' && newValue != null && newValue != undefined) {
        this.getDepartByBelong(newValue)
      }
    },
    addWebUrl () {
      this.webUrls.push({
        title: '',
        url: ''
      })
    },
    removeWebUrl (index) {
      if (this.webUrls.length > 1) {
        this.webUrls.splice(index, 1)
      }
    },
    handleFileUploadProgress(event, file, fileList) {
      this.upload.isUploading = true
    },
    // 文件上传成功处理
    handleFileSuccess(response, file, fileList) {
      this.upload.isUploading = false
      console.log(fileList)
      this.upload.files = fileList
    },
    formBelongChange(newValue) {
      this.getDepartByBelong(newValue)
    },
    getDepartByBelong(belong) {
      getDepartByBelong(belong).then(response => {
        this.departOptions = response.data
      })
    },
    contentChange(newValue) {
      this.form.content = newValue
    },
    /** 查询部门树 */
    // getSourceTree() {
    //   getSourceTree().then(response => {
    //     this.sourceTree = response.data
    //   })
    // },
    /** 查询栏目树 */
    getCategoryTree() {
      getCategoryTree({position: 2}).then(response => {
        this.categoryTree = response.data
      })
    },
    /** 查询Content列表 */
    getList() {
      this.loading = true;
      listContent(this.queryParams).then(response => {
        this.contentList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    // 类型 1text 2pdf 3video字典翻译
    typeFormat(row, column) {
      return this.selectDictLabel(this.typeOptions, row.type);
    },
    // 状态 0禁用 1启用字典翻译
    statusFormat(row, column) {
      if (row.status == 0) {
        return '审核未通过'
      } else if (row.status == 1) {
        return '审核通过'
      } else if (row.status == 2) {
        return '等待审核'
      }
    },
    // 取消按钮
    cancel() {
      this.open = false;
      this.reset();
    },
    // 表单重置
    reset() {
      this.form = {
        id: null,
        title: null,
        content: null,
        position: 2,
        cover: null,
        sortOrder: 0,
        belong: null,
        departId: null,
        categoryId: null,
        type: null,
        status: 2,
        createTime: null,
        createBy: null,
        updateTime: null,
        updateBy: null
      }
      this.webUrls = [{
        title: '',
        url: ''
      }]
      this.resetForm('form')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.resetForm("queryForm");
      this.handleQuery();
    },
    // 多选框选中数据
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.single = selection.length !== 1
      this.multiple = !selection.length
    },
    /** 新增按钮操作 */
    handleAdd() {
      this.reset();
      this.open = true;
      this.title = "添加Content";
    },
    /** 修改按钮操作 */
    handleUpdate(row) {
      this.reset();
      const id = row.id || this.ids
      getContent(id).then(response => {
        this.form = response.data;
        this.form.belong = '' + this.form.belong
        this.getDepartByBelong(this.form.belong)
        this.open = true
        this.title = '修改Content'
        if ( response.data.type == 4 ) {
          const files = JSON.parse(response.data.content)
          this.upload.files = files.List
        } else if ( response.data.type == 5 ) {
          const urls = JSON.parse(response.data.content)
          this.webUrls = urls.List
        }
      })
    },
    /** 提交按钮 */
    submitForm() {
      this.$refs["form"].validate(valid => {
        if (valid) {
          this.form.position = 2

          if (this.form.type == 4) {
            let showList = this.upload.files.map(file => {
              let suffix = file.name.split('.')[file.name.split('.').length - 1]
              let fileName = file.name
              let url = file.response.url
              let show = '<a href=\'' + url + '\'>[' + suffix + ']' + fileName + '</a>'
              return show
            })

            let res = {}
            res.List = this.upload.files
            res.showList = showList

            this.form.content = JSON.stringify(res)
          } else if (this.form.type == 5) {
            let showList = this.webUrls.map(webUrl => {
              return  '<a href="' +webUrl.url+ '">[链接]'+ webUrl.title +'</a>'
            })

            let res = {}
            res.List = this.webUrls
            res.showList = showList

            this.form.content = JSON.stringify(res)
          }

          this.form.createTime = moment(this.form.createTime).utcOffset(480).format('YYYY-MM-DD HH:mm:ss')

          if (this.form.id != null) {
            updateContent(this.form).then(response => {
              this.msgSuccess("修改成功");
              this.open = false;
              this.getList();
            });
          } else {
            addContent(this.form).then(response => {
              this.msgSuccess("新增成功");
              this.open = false;
              this.getList();
            });
          }

          this.webUrls = [{
            title: '',
            url: ''
          }]
        }
      });
    },
    /** 删除按钮操作 */
    handleDelete(row) {
      const ids = row.id || this.ids;
      this.$confirm('是否确认删除Content编号为"' + ids + '"的数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(function () {
        return delContent(ids);
      }).then(() => {
        this.getList();
        this.msgSuccess("删除成功");
      }).catch(() => {
      });
    },
    /** 导出按钮操作 */
    handleExport() {
      const queryParams = this.queryParams;
      this.$confirm('是否确认导出所有Content数据项?', "警告", {
        confirmButtonText: "确定",
        cancelButtonText: "取消",
        type: "warning"
      }).then(() => {
        this.exportLoading = true;
        return exportContent(queryParams);
      }).then(response => {
        this.download(response.msg);
        this.exportLoading = false;
      }).catch(() => {
      });
    }
  }
};
</script>
